import { effect } from "./reactive.js";

// v-model
export function modelDirective(elementNode, attr, instance) {
    const vmodel = 'v-model';
    if (elementNode.hasAttribute(vmodel)) {
        const variable = elementNode.getAttribute(vmodel);
        effect(() => {
            elementNode.setAttribute('value', instance[variable]);
            elementNode.value = instance[variable];
        }
        );
        elementNode.addEventListener('input', () => instance[variable] = elementNode.value);

        elementNode.removeAttribute(vmodel);
    }
}

// v-bind
export function bindDirective(elementNode, attr, instance) {
    const { name, value } = attr;
    const reg = /^(v-bind:|:)([\s\S]+)/;
    const matched = name.match(reg);
    if (matched) {
        const attrName = matched[2];
        effect(() => {
            elementNode.setAttribute(attrName, instance[value]);
        }
        );

        elementNode.removeAttribute(matched[0]);
    }
}

// v-on
export function onDirective(elementNode, attr, instance) {
    const { name, value } = attr;
    const reg = /^(v-on:|@)([\s\S]+)/;
    const matched = name.match(reg);
    if (matched) {
        const eventName = matched[2];
        elementNode.addEventListener(eventName, instance[value]);

        elementNode.removeAttribute(matched[0]);
    }
}

export default [
    bindDirective,
    onDirective,
    modelDirective
]